package com.xyxy.platform.modules.service.trade.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.xyxy.platform.modules.entity.trade.Goods;
import com.xyxy.platform.modules.entity.trade.OrderComment;
import com.xyxy.platform.modules.entity.trade.OrderGoods;
import com.xyxy.platform.modules.entity.trade.OrderInfo;
import com.xyxy.platform.modules.entity.trade.OrderInfoExample;
import com.xyxy.platform.modules.repository.mybatis.trade.OrderCommentMapper;
import com.xyxy.platform.modules.repository.mybatis.trade.OrderGoodsMapper;
import com.xyxy.platform.modules.repository.mybatis.trade.OrderInfoDto;
import com.xyxy.platform.modules.repository.mybatis.trade.OrderInfoMapper;
import com.xyxy.platform.modules.service.trade.GoodsService;
import com.xyxy.platform.modules.service.trade.OrderService;
import com.xyxy.platform.modules.service.trade.utils.ImgUtils;
import com.xyxy.platform.modules.service.trade.vo.GoodsDto;
import com.xyxy.platform.modules.service.trade.vo.Order;
import com.xyxy.platform.modules.service.trade.vo.OrderCommentDto;
import com.xyxy.platform.modules.service.trade.vo.OrderStatusEnum;

/**
 *
 * @author vic E-mail: 251361939@qq.com
 * @version 创建时间：2015年12月21日 下午2:42:30 
 */
@Service
public class OrderServiceImpl implements OrderService {

	Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

	final SimpleDateFormat fullSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	@Autowired
	private OrderGoodsMapper orderGoodsMapper;
	@Autowired
	private OrderCommentMapper orderCommentMapper;
	@Autowired
	private GoodsService goodsService;

	@Override
	public List<OrderInfo> findOrderInfoList(int option,String memberId, String type,int page, int rows) {
		if(StringUtils.isEmpty(memberId) || page<0 || rows <0){
			return null;
		}
		OrderInfoExample orderInfoExample = new OrderInfoExample();
		OrderInfoExample.Criteria criteria = orderInfoExample.or();
		if(option == 1){
			criteria.andMemberIdEqualTo(Long.parseLong(memberId));
		}else if(option == 2){
			criteria.andSallIdEqualTo(Long.parseLong(memberId));
		}
		if(!StringUtils.isEmpty(type)){
			criteria.andOrderStatusEqualTo(Integer.parseInt(type));
		}
		criteria.andIsDelEqualTo(0);

		PageHelper.startPage(page, rows);
		List<OrderInfo> list = new ArrayList<OrderInfo>();
		List<OrderInfo> orderInfoList = orderInfoMapper.selectByExample(orderInfoExample);
		for (OrderInfo orderInfo : orderInfoList) {
			Goods  goods = goodsService.selectByPrimaryId(orderInfo.getGoodsId());
			orderInfo.setGoods(goods);
			list.add(orderInfo);
		}
		
		return list;
	}


	@Override
	public List<OrderInfo> getMemberOrder(long memberid, String orderSn,String referer) {
		OrderInfoExample orderInfoExample = new OrderInfoExample();
		if(orderSn!=null){
			orderInfoExample.or().andMemberIdEqualTo(memberid).andOrderSnEqualTo(orderSn);		
		}else{
			orderInfoExample.or().andMemberIdEqualTo(memberid).andRefererEqualTo(referer);		
		}
		List<OrderInfo> orderInfoList = orderInfoMapper.selectByExample(orderInfoExample);
		if(orderInfoList != null && orderInfoList.size()> 0){
			return orderInfoList;
		}
		return null;
	}

	@Override
	public OrderInfo getSallOrder(long memberid, String orderSn) {
		OrderInfoExample orderInfoExample = new OrderInfoExample();
		orderInfoExample.or().andSallIdEqualTo(memberid).andOrderSnEqualTo(orderSn);
		List<OrderInfo> orderInfoList = orderInfoMapper.selectByExample(orderInfoExample);
		if(orderInfoList != null && orderInfoList.size()> 0){
			return orderInfoList.get(0);
		}
		return null;
	}

	@Override
	public boolean removeMemberOrder(long memberid, String orderSn) {
		boolean flag =false;
		 List<OrderInfo> orderInfoList= getMemberOrder(memberid,orderSn,null);
		 OrderInfo orderInfo =orderInfoList.get(0);
		if(orderInfo != null){
			int orderStatus = orderInfo.getOrderStatus();
			//判断状态是否可删除
			boolean isDel = false;
			if(orderStatus == 0 || orderStatus == 5 || orderStatus == 7){
				isDel = true;
			}
			if(isDel){
				OrderInfo tempOrderInfo = new OrderInfo();
				tempOrderInfo.setOrderId(orderInfo.getOrderId());
				tempOrderInfo.setIsDel(1);
				flag = orderInfoMapper.updateByPrimaryKeySelective(tempOrderInfo) > 0;
			}
		}
		return flag;
	}

	@Override
	public boolean removeSallOrder(long sallId, String orderSn) {
		boolean flag =false;
		OrderInfo orderInfo = getSallOrder(sallId,orderSn);
		if(orderInfo != null){
			int orderStatus = orderInfo.getOrderStatus();
			//判断状态是否可删除
			boolean isDel = false;
			if(orderStatus == 0 || orderStatus == 5 || orderStatus == 7){
				isDel = true;
			}
			if(isDel){
				OrderInfo tempOrderInfo = new OrderInfo();
				tempOrderInfo.setOrderId(orderInfo.getOrderId());
				tempOrderInfo.setIsDel(1);
				flag = orderInfoMapper.updateByPrimaryKeySelective(tempOrderInfo) > 0;
			}
		}
		return flag;
	}

	@Override
	public boolean cancelMemberOrder(long memberId, String orderSn) {
		boolean flag = false;
		 List<OrderInfo> orderInfoList= getMemberOrder(memberId,orderSn,null);
		 OrderInfo orderInfo =orderInfoList.get(0);
		if(orderInfo!=null){
			OrderInfo tempOrderInfo = new OrderInfo();
			tempOrderInfo.setOrderStatus(OrderStatusEnum.CLOSE.getValue());
			tempOrderInfo.setOrderId(orderInfo.getOrderId());
			flag = orderInfoMapper.updateByPrimaryKeySelective(tempOrderInfo) > 0;
		}
		return flag;
	}

	@Override
	public boolean cancelSallOrder(long sallId, String orderSn) {
		boolean flag = false;
		OrderInfo orderInfo = getSallOrder(sallId, orderSn);
		if(orderInfo!=null){
			OrderInfo tempOrderInfo = new OrderInfo();
			tempOrderInfo.setOrderStatus(OrderStatusEnum.CLOSE.getValue());
			tempOrderInfo.setOrderId(orderInfo.getOrderId());
			flag = orderInfoMapper.updateByPrimaryKeySelective(tempOrderInfo) > 0;
		}
		return flag;
	}

	@Override
	public boolean submitOrderInfo(Order order) {
		boolean flag = false;
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setAddressId(order.getAddressId());
		orderInfo.setPostscript(order.getPostscript());
		orderInfo.setMemberId(order.getMemberid());
		orderInfo.setSallId(order.getMemberid());
		orderInfo.setOrderStatus(order.getStatus());
		orderInfo.setGoodsAmount(new BigDecimal(order.getGoodPrice()).multiply(new BigDecimal(order.getNumber())));
		orderInfo.setOrderAmount(orderInfo.getGoodsAmount());
		Date currDate = new Date();
		orderInfo.setCreateTime(currDate);
		orderInfo.setConfirmTime(currDate);
		orderInfo.setServerStartTime(order.getTime());
		orderInfo.setIsDel(0);
		orderInfo.setOrderSn(order.getOrderSn());
		orderInfo.setPayStatus(order.getPayStatus());
		orderInfo.setGoodsId(order.getGoods().getGoodsId());
		orderInfo.setReferer(order.getReferer());
		flag = orderInfoMapper.insert(orderInfo) > 0;
		if(!flag){
			throw new RuntimeException();
		}

		OrderGoods orderGoods = new OrderGoods();
		orderGoods.setOrderId(orderInfo.getOrderId());
		orderGoods.setGoodsId(order.getGoods().getGoodsId());
		orderGoods.setGoodsName(order.getGoods().getGoodsName());
		orderGoods.setGoodsSn(order.getGoods().getGoodsSn());
		orderGoods.setGoodsNumber(order.getNumber());
		orderGoods.setGoodsPrice(order.getGoods().getShopPrice());
		flag = orderGoodsMapper.insert(orderGoods) > 0;
		if(!flag){
			throw new RuntimeException();
		}

		return true;
	}

	@Override
	public boolean saveOrderComment(OrderCommentDto orderCommentDto) {
		boolean flag =false;
		long memberId= Long.parseLong(orderCommentDto.getMemberId());
		String orderSn = orderCommentDto.getOrderSn();
		 List<OrderInfo> orderInfoList= getMemberOrder(memberId,orderSn,null);
		 OrderInfo orderInfo =orderInfoList.get(0);
		if(orderInfo == null){
			logger.info(":会员当前订单"+orderCommentDto.getOrderSn()+"不存在");
			return flag;
		}

		String imgsIds = orderCommentDto.getImgsIds();
		long pckid = 0 ;//图片分组id  默认为0 ，0为图片为空
		//处理评论图片
		if(!StringUtils.isEmpty(imgsIds)){
			String[] imgs = StringUtils.split(imgsIds, ",");
			String tempImgPath = ImgUtils.getTempImgPath();
			String memberOrderCommentPath = ImgUtils.getMemberOrderCommentPath();
			if(!StringUtils.isEmpty(tempImgPath) && !StringUtils.isEmpty(memberOrderCommentPath)){
				memberOrderCommentPath+=orderCommentDto.getOrderSn();
				for(String str : imgs){
					//TODO:copy临时文件

					//TODO:存入图片组
				}
			}else{
				if(StringUtils.isEmpty(tempImgPath))
					logger.info("临时图片路径未设置");
				if(StringUtils.isEmpty(memberOrderCommentPath))
					logger.info("订单评论图片路径未设置");
			}
		}



		//持久化数据
		OrderComment orderComment = new OrderComment();
		orderComment.setMemberId(memberId);
		orderComment.setOrderId(orderInfo.getOrderId());
		orderComment.setDescribeNo(orderCommentDto.getDescribe());
		orderComment.setQuality(orderCommentDto.getQuality());
		orderComment.setAttitude(orderCommentDto.getAttitude());
		orderComment.setTags(orderCommentDto.getTags());
		orderComment.setDetailed(orderCommentDto.getDetailed());
		orderComment.setImgsPkgId(pckid);
		orderComment.setUpdateTime(new Date());
		orderComment.setIdDel(1);
		flag = orderCommentMapper.insert(orderComment)>0;

		return flag;
	}


	@Override
	public List<OrderInfoDto> findOrderInfoDtoList(int option, String memberId, String type, int page, int rows) {
		List<OrderInfoDto> orderInfoDtoList = null ;
		List<OrderInfo> orderInfoList = findOrderInfoList(option, memberId, type, page, rows);
		if(orderInfoList!=null && orderInfoList.size()> 0){
			orderInfoDtoList = new ArrayList<OrderInfoDto>();
			OrderInfoDto orderInfoDto = null ;
			for(OrderInfo orderInfo : orderInfoList){
				orderInfoDto = new OrderInfoDto();
				orderInfoDto.setOrderInfo(orderInfo);
				long orderId = orderInfo.getOrderId();
				//根据订单号获取商品列表
				List<GoodsDto> goodsDtoList = goodsService.selectGoodsDtoByOrderId(orderId);
				orderInfoDto.setGoodsDtoList(goodsDtoList);
				orderInfoDtoList.add(orderInfoDto);
			}
		}
		return orderInfoDtoList;
	}


	@Override
	public int updateOrderInfo(OrderInfo orderInfo) {
		return orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
	}

}
